package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Result;
import com.example.entity.Product;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 商品控制器
 */
@RestController
@RequestMapping("/api/product")
public class ProductController {
    
    @Autowired
    private ProductService productService;
    
    /**
     * 创建商品
     */
    @PostMapping
    public Result<Product> create(@RequestBody Product product) {
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        productService.save(product);
        return Result.success(product);
    }
    
    /**
     * 更新商品
     */
    @PutMapping("/{id}")
    public Result<Product> update(@PathVariable Long id, @RequestBody Product product) {
        product.setId(id);
        product.setUpdateTime(LocalDateTime.now());
        productService.updateById(product);
        return Result.success(product);
    }
    
    /**
     * 删除商品（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        productService.removeById(id);
        return Result.success();
    }
    
    /**
     * 根据ID查询商品
     */
    @GetMapping("/{id}")
    public Result<Product> getById(@PathVariable Long id) {
        Product product = productService.getById(id);
        return Result.success(product);
    }
    
    /**
     * 查询所有商品
     */
    @GetMapping("/list")
    public Result<List<Product>> list() {
        List<Product> list = productService.list();
        return Result.success(list);
    }
    
    /**
     * 分页查询商品
     */
    @GetMapping("/page")
    public Result<Page<Product>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<Product> page = new Page<>(current, size);
        Page<Product> result = productService.page(page);
        return Result.success(result);
    }
    
    /**
     * 根据分类查询商品
     */
    @GetMapping("/category/{category}")
    public Result<List<Product>> getByCategory(@PathVariable String category) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("category", category);
        List<Product> list = productService.list(wrapper);
        return Result.success(list);
    }
}
